<?php
  /**
   * 基础分页的相同代码封装，使前台的代码更少
   * @param $count 要分页的总记录数
   * @param int $pagesize 每页查询条数
   * @return \Think\Page
   */
 function getpage($count,$pagesize=10){

     $p=new Think\Page($count,$pagesize);

     $p->setConfig('prev','上一页');

     $p->setConfig('next','下一页');

     $p->setConfig('last','尾页');

     $p->setConfig('first','首页');
 
     $p->setConfig('theme','%HEADER%  %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% ');
      
     $p->lastSuffix =false;//最后一页是否显示总页数
     
     return $p; 

 }
 /*
 *返回json格式提示
 *1--成功  2--失败
 * return  ;
 */
function message($code=0,$msg='',$url='')
	{
		
		$message=!empty($url)?array('code'=>$code,'msg'=>$msg,'url'=>$url):array('code'=>$code,'msg'=>$msg);
		
		echo json_encode($message);	
		
		exit;  
	}
 /*
 *判断是否有空字段
 *return  false or true
 */	
function is_empty(){
	
	$arr=func_get_args();
	
	if(count($arr)>0){
		
		$is_empty=true;
		
		foreach($arr as $k=>$v){
	       
   		   $is_empty=$is_empty&&!empty($v); 
		}
		
		return $is_empty;
		
	}
	 
	return false; 
}

/*
*打印信息
*/
function p($str,$flag=0){
	
	echo '<pre>';
	
	var_dump($str);
	
	!empty($flag)?'':exit;
	
}
//检测手机号
function is_mobile($str){

   if (preg_match('/^1(([3][0-9])|([7][0-9])|([5][0-9])|([4][0-9])|([7][0-9])|([8][0-9]))[0-9]{8}/', $str)) {	 
   	  return true;
   }
   
   return false;
}



/**
 * 请求接口返回内容
 * @param  string $url [请求的URL地址]
 * @param  string $params [请求的参数]
 * @param  int $ipost [是否采用POST形式]
 * @return  string
 */
function juhecurl($url,$params=false,$ispost=1){
    $httpInfo = array();
    $ch = curl_init();
 
    curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
    curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
    curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
    if( $ispost )
    {
        curl_setopt( $ch , CURLOPT_POST , true );
        curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
        curl_setopt( $ch , CURLOPT_URL , $url );
    }
    else
    {
        if($params){
            curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
        }else{
            curl_setopt( $ch , CURLOPT_URL , $url);
        }
    }
    $response = curl_exec( $ch );
    if ($response === FALSE) {
        //echo "cURL Error: " . curl_error($ch);
        return false;
    }
    $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
    $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
    curl_close( $ch );
    return $response;
}

/**
 * 判断是否为合法的身份证号码
 * @param $mobile
 * @return int
 */
function isCreditNo($vStr){
  $vCity = array(
    '11','12','13','14','15','21','22',
    '23','31','32','33','34','35','36',
    '37','41','42','43','44','45','46',
    '50','51','52','53','54','61','62',
    '63','64','65','71','81','82','91'
  );
  if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) return false;
  if (!in_array(substr($vStr, 0, 2), $vCity)) return false;
  $vStr = preg_replace('/[xX]$/i', 'a', $vStr);
  $vLength = strlen($vStr);
  if ($vLength == 18) {
    $vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
  } else {
    $vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
  }
  if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) return false;
  if ($vLength == 18) {
    $vSum = 0;
    for ($i = 17 ; $i >= 0 ; $i--) {
      $vSubStr = substr($vStr, 17 - $i, 1);
      $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr , 11));
    }
    if($vSum % 11 != 1) return false;
  }
  return true;
}
/*
*
*  获取客户端的IP地址
*/
function get_ip(){
        $ip='';
        if (isset($_SERVER)){
            if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
                $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
            } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
                $ip = $_SERVER["HTTP_CLIENT_IP"];
            } else {
                $ip = $_SERVER["REMOTE_ADDR"];
            }
        } else {
            if (getenv("HTTP_X_FORWARDED_FOR")){
                $ip = getenv("HTTP_X_FORWARDED_FOR");
            } else if (getenv("HTTP_CLIENT_IP")) {
                $ip = getenv("HTTP_CLIENT_IP");
            } else {
                $ip = getenv("REMOTE_ADDR");
            }
        }
        return $ip;
    }
  /*
*
*  调用淘宝IP的API接口查询城市信息
*/
 function get_city($ip){
        $city_info = 'http://ip.taobao.com/service/getIpInfo.php?ip='.$ip;
        $info = json_decode(file_get_contents($city_info));
        $province = $info->data->region;
        $city = $info->data->city;
       // $data = $province.$city;
        return $city;
}

/*
*
*   截取字符串
*
*/
 
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)
{
   if(mb_strlen($str,$charset)>$length)
   {
	    if(function_exists("mb_substr")){
            if($suffix)
                return mb_substr($str, $start, $length, $charset)."...";
            else
                return mb_substr($str, $start, $length, $charset);
        }elseif(function_exists('iconv_substr')) {
            if($suffix)
                return iconv_substr($str,$start,$length,$charset)."...";
            else
                return iconv_substr($str,$start,$length,$charset);
        }
        $re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
        $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
        $re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
        $re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
        if($suffix) return $slice."…";
        return $slice;
   }else{
	   
	   return $str;
   }
   
}

/*
*
*    星号 代替
*   flag=1 --显示第一个字 其他星号代替  flag=2, 中间取四个 星号 代替
*/

function  hid_star($str, $flag=1){
	
	 $len=mb_strlen($str,'UTF-8'); //中文字符算一个
 
	 if(!empty($str)){
          if($flag==1){
			  
			  if($len>1){
				  
				  for($i=0;$i<$len-1; $i++){
					  $star.=$star.'*';
				  }
				  
			  }
			  
			  $str=mb_substr($str,0,1,'utf-8').$star;
			  
		  } 
		  elseif($flag==2){
			  
			  $str=($len==18)?str_replace(substr($str,4,10),'****',$str):str_replace(substr($str,5,4),'****',$str);
 
		  }
	     elseif($flag==3){
			  
			  $str=str_replace(substr($str,4,4),'****',$str);
 
		  }
	 }
	 return  $str;
	 
}
 /*删除文章内容图片（也就是删除编辑器上传的图片）*/
function delete_img($content){
    //匹配并删除图片

    $img_path = "/<img.*src=\"([^\"]+)\"/U";

    $matches = array();
    preg_match_all($img_path, $content, $matches);

    foreach($matches[1] as $img_url){
    //strpos(a,b) 匹配a字符串中是否包含b字符串 包含返回true
        if(strpos($img_url, 'emoticons')===false){
            $host = 'http://' . $_SERVER['HTTP_HOST'] . '/';
            $filepath = str_replace($host,'',$img_url);
            if($filepath == $img_url) $filepath = substr($img_url, 1);
            @unlink($filepath);
            $filedir  = dirname($filepath);
            $files = scandir($filedir);
            if(count($files)<=2)@rmdir($filedir);//如果是./和../,直接删除文件夹
        }
    }
    unset($matches);
}

/*删除文件夹以及子文件夹中的文件*/
function del_dir($dir){
	
	if(is_dir($dir)==false){
		
		return false;
	}
	
	$dh=opendir($dir);
	
	while(($file=readdir($dh))!=false){
		
		if($file!='.'&&$file!='..'){
			
			 is_dir($dir.DIRECTORY_SEPARATOR.$file)?del_dir($dir.DIRECTORY_SEPARATOR.$file):unlink($dir.DIRECTORY_SEPARATOR.$file);
		 
		}
		
	}
	
	if(readdir($dh)==false){
		closedir($dh);
		return @rmdir($dir);
	}
	
	 
}

/**
 * 异步将远程链接上的内容(图片或内容)写到本地  (针对微信服务器头像图片下载到自己的服务器,因为微信头像url不是图片格式后缀)
 * 
 * @param  $url
 *            远程地址
 * @param   $saveName
 *            保存在服务器上的文件名
 * @param   $path
 *            保存路径
 * @return boolean
 */	
	
function put_file_from_url_content($url, $saveName, $path) {
    // 设置运行时间为无限制
    set_time_limit ( 0 );
    
    $url = trim ( $url );
    $curl = curl_init ();
    // 设置你需要抓取的URL
    curl_setopt ( $curl, CURLOPT_URL, $url );
    // 设置header
    curl_setopt ( $curl, CURLOPT_HEADER, 0 );
    // 设置cURL 参数，要求结果保存到字符串中还是输出到屏幕上。
    curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
    // 运行cURL，请求网页
    $file = curl_exec ( $curl );
    // 关闭URL请求
    curl_close ( $curl );
    // 将文件写入获得的数据
    $filename = $path . $saveName;
    $write = @fopen ( $filename, "w" );
    if ($write == false) {
        return false;
    }
    if (fwrite ( $write, $file ) == false) {
        return false;
    }
    if (fclose ( $write ) == false) {
        return false;
    }
	
	return true;
}	
//微信昵称为特殊表情字符 出错问题
function removeByte4($str)
{
	
    return preg_replace('/[\xF0-\xF7].../s','', $str);
}
//js编码过的url汉字参数进行解码
function unescape($str) {
    $str = rawurldecode($str);
    preg_match_all("/%u.{4}|&#x.{4};|&#\d+;|.+/U",$str,$r);
    $ar = $r[0];
    foreach($ar as $k=>$v) {
        if(substr($v,0,2) == "%u")
            $ar[$k] = iconv("UCS-2","utf-8",pack("H4",substr($v,-4)));
            elseif(substr($v,0,3) == "&#x")
            $ar[$k] = iconv("UCS-2","utf-8",pack("H4",substr($v,3,-1)));
            elseif(substr($v,0,2) == "&#") {
                $ar[$k] = iconv("UCS-2","utf-8",pack("n",substr($v,2,-1)));
            }
    }
    return join("",$ar);
}  

 function mobile_or_pc()
{
    $_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';
    $mobile_browser = '0';
    if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT'])))
        $mobile_browser++;
        if ((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']), 'application/vnd.wap.xhtml+xml') !== false))
            $mobile_browser++;
            if (isset($_SERVER['HTTP_X_WAP_PROFILE']))
                $mobile_browser++;
                if (isset($_SERVER['HTTP_PROFILE']))
                    $mobile_browser++;
                    $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
                    $mobile_agents = array(
                        'w3c ', 'acs-', 'alav', 'alca', 'amoi', 'audi', 'avan', 'benq', 'bird', 'blac',
                        'blaz', 'brew', 'cell', 'cldc', 'cmd-', 'dang', 'doco', 'eric', 'hipt', 'inno',
                        'ipaq', 'java', 'jigs', 'kddi', 'keji', 'leno', 'lg-c', 'lg-d', 'lg-g', 'lge-',
                        'maui', 'maxo', 'midp', 'mits', 'mmef', 'mobi', 'mot-', 'moto', 'mwbp', 'nec-',
                        'newt', 'noki', 'oper', 'palm', 'pana', 'pant', 'phil', 'play', 'port', 'prox',
                        'qwap', 'sage', 'sams', 'sany', 'sch-', 'sec-', 'send', 'seri', 'sgh-', 'shar',
                        'sie-', 'siem', 'smal', 'smar', 'sony', 'sph-', 'symb', 't-mo', 'teli', 'tim-',
                        'tosh', 'tsm-', 'upg1', 'upsi', 'vk-v', 'voda', 'wap-', 'wapa', 'wapi', 'wapp',
                        'wapr', 'webc', 'winw', 'winw', 'xda', 'xda-'
                    );
                    if (in_array($mobile_ua, $mobile_agents))
                        $mobile_browser++;
                        if (strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false)
                            $mobile_browser++;
                            // Pre-final check to reset everything if the user is on Windows
                            if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false)
                                $mobile_browser = 0;
                                // But WP7 is also Windows, with a slightly different characteristic
                                if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false)
                                    $mobile_browser++;
                                    if ($mobile_browser > 0)
                                        return true;
                                        else
                                            return false;
}

/**
 * 等比例生成缩略图
 * @param $imgSrc
 * @param $resize_width
 * @param $resize_height
 * @param $isCut
 * @author james.ou 2011-11-1
 */
 function reSizeImg($imgSrc, $resize_width, $resize_height, $isCut = false) {
    //图片的类型
    $type = substr(strrchr($imgSrc, "."), 1);
    //初始化图象
    if ($type == "jpg") {
        $im = imagecreatefromjpeg($imgSrc);
    }
    if ($type == "gif") {
        $im = imagecreatefromgif($imgSrc);
    }
    if ($type == "png") {
        $im = imagecreatefrompng($imgSrc);
    }
    //目标图象地址
    $full_length = strlen($imgSrc);
    $type_length = strlen($type);
    $name_length = $full_length - $type_length;
    $name = substr($imgSrc, 0, $name_length - 1);
    $dstimg = $name.'_thumb.'.$type;
    
    $width = imagesx($im);
    $height = imagesy($im);
    
    //生成图象
    //改变后的图象的比例
    $resize_ratio = ($resize_width) / ($resize_height);
    //实际图象的比例
    $ratio = ($width) / ($height);
    if (($isCut) == 1) { //裁图
        if ($ratio >= $resize_ratio) { //高度优先
            $newimg = imagecreatetruecolor($resize_width, $resize_height);
            imagecopyresampled($newimg, $im, 0, 0, 0, 0, $resize_width, $resize_height, (($height) * $resize_ratio), $height);
            ImageJpeg($newimg, $dstimg);
        }
        if ($ratio < $resize_ratio) { //宽度优先
            $newimg = imagecreatetruecolor($resize_width, $resize_height);
            imagecopyresampled($newimg, $im, 0, 0, 0, 0, $resize_width, $resize_height, $width, (($width) / $resize_ratio));
            ImageJpeg($newimg, $dstimg);
        }
    } else { //不裁图
        if ($ratio >= $resize_ratio) {
            $newimg = imagecreatetruecolor($resize_width, ($resize_width) / $ratio);
            imagecopyresampled($newimg, $im, 0, 0, 0, 0, $resize_width, ($resize_width) / $ratio, $width, $height);
            ImageJpeg($newimg, $dstimg);
        }
        if ($ratio < $resize_ratio) {
            $newimg = imagecreatetruecolor(($resize_height) * $ratio, $resize_height);
            imagecopyresampled($newimg, $im, 0, 0, 0, 0, ($resize_height) * $ratio, $resize_height, $width, $height);
            ImageJpeg($newimg, $dstimg);
        }
    }
    ImageDestroy($im);
}

/**
 * 
 * 原图与缩略图拆分
 * 
 */
function split_original($img_url){
 
    
    if(!empty($img_url)){
        
        $img_url_arr=explode('.',$img_url);
       
        return str_replace('.'.$img_url_arr[intval(count($img_url_arr))-1],'_thumb.'.$img_url_arr[intval(count($img_url_arr))-1], $img_url);
 
    }
    
    return '';
}
 